package com.glowdayz.glowmee;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.ImageDownloader;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AdminTableCMD;

public class ViewNotice extends Activity {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	TextView noticeTitle = null, noticeDate = null, boardText = null;
	ImageView noticeTextImg = null;
	
	int paramId = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_notice);
		
		am.addActivity(this);
		
		Intent fromIntent = getIntent();
		paramId = fromIntent.getIntExtra("PARAM_id", 0);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setVisibility(View.GONE);
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("공지사항");
		
		noticeTitle = (TextView) findViewById(R.id.noticeTitle);
		noticeDate = (TextView) findViewById(R.id.noticeDate);
		boardText = (TextView) findViewById(R.id.boardText);
		noticeTextImg = (ImageView) findViewById(R.id.noticeTextImg);
		
		(new NoticeWorker()).execute();
	}
	
	public class NoticeWorker extends AsyncTask<Object, AdminTableCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ViewNotice.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			String url = getResources().getString(R.string.server_url) + "/glowmee/noticeXml.do?idAdmin=" + paramId;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idAdminBoard = 0;
				String boardTitle = null;
				String boardText = null;
				String create_date = null;
				String thumbnail = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("idAdminBoard")) {
							parser.next();
							idAdminBoard = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("boardTitle")) {
							parser.next();
							boardTitle = parser.getText();
						} else if (tag.equals("boardText")) {
							parser.next();
							boardText = parser.getText();
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							AdminTableCMD item = new AdminTableCMD(idAdminBoard, boardTitle, boardText, thumbnail, create_date);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AdminTableCMD... param) {
			noticeTitle.setText(param[0].getBoardTitle());
			noticeDate.setText(param[0].getCreate_date());
			boardText.setText(param[0].getBoardText());
			
			if (!param[0].getModified_date().equals("null")) {
				noticeTextImg.setVisibility(View.VISIBLE);
				ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + param[0].getModified_date().trim(), noticeTextImg);
			} else {
				noticeTextImg.setVisibility(View.GONE);
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ViewNotice.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new NoticeWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

}
